package de.uni_saarland.coli.doclists.data.btree;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map.Entry;

import de.uni_saarland.coli.doclists.index.IDiscIO;

/**
 * @author stefan
 *
 * In memory id,data mapping.
 * Uses a <code>HashMap<T></code>
 * 
 * @param <T> Type of value
 */
public class MemoryMapData<T> implements IMapData<T>, IDiscIO, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6149319995098103891L;
	private HashMap<Integer,T> map;
	
	/**
	 * Constructor. 
	 */
	public MemoryMapData() {
		this.map = new HashMap<Integer,T>(); 
	}
	
	@Override
	public T add(int id, T data) {
		this.map.put(id, data);
		return data;
	}

	@Override
	public T get(int id) {
		return this.map.get(id);
	}
	
	@Override
	public boolean containsKey(int key) {
		return this.map.containsKey(key);
	}

	@SuppressWarnings("unchecked")
	public void open(String path, String baseName) {
		this.map = new HashMap<Integer,T>(); 

		FileInputStream fis = null;
		ObjectInputStream in = null;
		
		try {
			fis = new FileInputStream(path + "/" + baseName + ".map");
			in = new ObjectInputStream(fis);
			this.map = (HashMap<Integer, T>) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save(String path, String baseName) {
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream(path + "/" + baseName + ".map");
			out = new ObjectOutputStream(fos);
			out.writeObject(this.map);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		
		for (Entry<Integer,T> iter : this.map.entrySet()) {
		//	sb.append("value:\n").append(iter.getKey()).append("\nData:\n");
			sb.append(iter.getValue().toString());
			sb.append("\n");
		}
		
		return sb.toString();
	}
}
